package com.ds.common.org.expression.org;

import com.ds.common.expression.ParseException;
import com.ds.common.expression.function.AbstractFunction;
import com.ds.org.Org;
import com.ds.org.OrgManager;
import com.ds.org.OrgNotFoundException;
import com.ds.server.OrgManagerFactory;

import java.util.List;

/**
 * 取得指定组织的下级组织（包括直接的和间接的），包括自己本身
 * <p>
 * Title: JDSORG组织机构中间件
 * </p>
 * <p>
 * Description:
 * </p>
 * <p>
 * Copyright: jds Copyright (c) 2003-2008
 * </p>
 * <p>
 * Company: www.justdos.net
 * </p>
 *
 * @author wenzhangli
 * @version 2.0
 */
public class GetAllChildrenPlusSelfOrg extends AbstractFunction {

    public Org[] perform(Object param1) throws ParseException {
        if (param1 == null) {
            return new Org[0];
        }
        // 组织机构的标识
        if (param1 instanceof String) {
            String orgId = (String) param1;
            OrgManager accountManager = OrgManagerFactory.getOrgManager();
            try {
                Org org = accountManager.getOrgByID(orgId);
                return perform(org);
            } catch (OrgNotFoundException e) {
                return new Org[0];
            }
        }

        // 组织机构对象
        if (param1 instanceof Org) {
            Org org = (Org) param1;


            List<Org> orglist = org.getChildrenRecursivelyList();
            Org[] orgs = orglist.toArray(new Org[orglist.size()]);

            int size = orgs.length;
            Org[] result = new Org[size + 1];
            result[0] = org;
            System.arraycopy(orgs, 0, result, 1, size);
            return result;
        }
        throw new ParseException("Invalid parameter type in:" + this.getClass().getName() + ", param1 is " + param1.getClass().getName());
    }
}